package com.sherlocky.learning.java11.http;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * Java 9 开始引入的一个处理 HTTP 请求的孵化 HTTP Client API，
 * 该 API 支持同步和异步，而在 Java 11 中已经为正式可用状态。
 *
 * @author: zhangcx
 * @date: 2019/9/26 18:23
 */
public class HTTPClientAPISample {
    public static void main(String[] args) throws IOException, InterruptedException {
        var request = HttpRequest.newBuilder()
                .uri(URI.create("http://www.sherlocky.com"))
                //.header("Cookie","xxx")
                .GET() // 可省略，默认即为GET
                .timeout(Duration.ofMillis(5000))
                .build();
        var client = HttpClient.newHttpClient();

        // 同步
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body().length());

        HttpClient client2 = HttpClient.newBuilder()
                .connectTimeout(Duration.ofMillis(5000))
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build();
        // 异步
        CompletableFuture<String> result = client2.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body);
        try {
            System.out.println(result.get().length());
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        /**
         * 还支持 设置超时时间、设置authenticator、设置header、POST表单、POST JSON、文件上传、文件下载、并发请求、HTTP2、WebSocket、reactive streams
         * https://segmentfault.com/a/1190000016555671
         */
    }
}
